package com.bwie.sms.consumer;

import com.bwie.common.domain.pojo.User;
import com.bwie.sms.feign.SystemFeignService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;

/**
 * @Author: Gd
 * @package: com.bwie.sms.consumer
 * @Project: zg5_goods
 * @Name: LoginConsumer
 * @Date: 2024/4/29 17:20
 */
@Component
public class LoginConsumer {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private SystemFeignService systemFeignService;


    @RabbitListener(queuesToDeclare = @Queue("Send_Email_To_Mq"))
    public void loginConsumer(User user, Message message, Channel channel){

        String messageId = message.getMessageProperties().getMessageId();

            try {
                Long count = redisTemplate.opsForSet().add("Dek_Id", messageId);
                if (count == 1) {

                    try {
                        // 发送邮件
                        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
                        helper.setFrom(user.getUserEmail());
                        helper.setTo("3164866164qq.com");
                        helper.setSubject("登录成功，邮件通知");
                        helper.setText("您好，" + user.getUserName() + "欢迎您，登录成功");
                        helper.addAttachment("当前图片", new File("\"C:\\Users\\31648\\Pictures\\Screenshots\\屏幕截图 2023-11-23 162648.png\""));
                        javaMailSender.send(mimeMessage);
                    } catch (MessagingException e) {
                        throw new RuntimeException(e);
                    }

                    // 添加日志


                    // 确认消息
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                }
            }catch (IOException e) {

                // 删除
                redisTemplate.opsForSet().remove("Dek_Id", messageId);


                try {
                    // 回退消息
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                throw new RuntimeException(e);
            }


        }
    }

